package com.binguo.service;

import com.binguo.common.exception.ServiceException;
import com.binguo.model.api.vo.InitInfoVO;
import com.binguo.model.api.vo.InitVO;
import com.binguo.model.model.*;
import com.binguo.model.repository.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Optional;

import static com.binguo.common.exception.ErrorCode.CASHIER_DESK_NAME_EXISTS;
import static com.binguo.common.exception.ErrorCode.INVITE_CODE_ERROR;
import static com.binguo.common.exception.ErrorCode.PHONE_INVITE_CODE_BOTH_EMPTY;


/**
 * Created by haibang on 18/5/7.
 */
@Service
public class InitService {

    @Autowired
    ShopRepository shopRepository;

    @Autowired
    CashierDeskRepository cashierDeskRepository;

    @Autowired
    InitInfoRepository initInfoRepository;

    @Autowired
    BranchRepository branchRepository;

    @Resource
    CashierDeskExtendRepository cashierDeskExtendRepository;


    @Transactional
    public InitVO init(String inviteCode, String phone, String deviceId, String shopName, String cashierDeskName){
        Condition condition = new Condition(Shop.class);
        Example.Criteria criteria = condition.or();
                if(inviteCode != null){
                    criteria.andEqualTo("invitecode", inviteCode);
                }else if(phone != null){
                    criteria.andEqualTo("phone", phone);
                }else throw new ServiceException(PHONE_INVITE_CODE_BOTH_EMPTY);

        Optional<Shop> shopOptional = shopRepository.findByCondition(condition).stream().findFirst();
        if(!shopOptional.isPresent()){
            throw new ServiceException(INVITE_CODE_ERROR);
        }
        Shop shop = shopOptional.get();
        _checkCashierDeskName(shop.getId(), cashierDeskName);

        Condition branchContion = new Condition(Branch.class);
        branchContion.or().andEqualTo("shopId",shop.getId());
        List<Branch> branchList = branchRepository.findByCondition(branchContion);
        if (null == branchList || branchList.size() == 0){
            throw new ServiceException("不存在任何分店信息");
        }
        Branch branch = branchList.get(0);

        CashierDesk cashierDesk = CashierDesk.builder()
                .shopid(shop.getId())
                .shopname(shopName)
                .ccode(deviceId)
                .branchid(branch.getBranchId())
                .name(cashierDeskName).build();
        cashierDeskRepository.save(cashierDesk);
        Integer cashierDeskId = cashierDeskRepository.findBy("name", cashierDeskName).getId();

        CashierDeskExtend cashierDeskExtend = new CashierDeskExtend();
        cashierDeskExtend.setDeskId(cashierDeskId);
        cashierDeskExtend.setType(1);
        cashierDeskExtend.setStatus(1);
        cashierDeskExtend.setOnlineState(1);
        cashierDeskExtend.setBranchName(branch.getBranchName());
        cashierDeskExtend.setLastSyncTime(new Date());
        cashierDeskExtend.setDefaultChargePrice(0);
        cashierDeskExtendRepository.save(cashierDeskExtend);

        //用于服务器判断收银台设备是否绑定
        InitInfo initInfo = InitInfo.builder()
                .deviceid(deviceId)
                .cashierdeskid(cashierDeskId)
                .shopid(shop.getId()).build();
        initInfoRepository.save(initInfo);


       return InitVO.builder()
                .cashierDeskId(cashierDeskId)
                .cashierDeskName(cashierDeskName)
                .shopId(shop.getId()).build();
    }

    private void _checkCashierDeskName(Integer shopId, String cashierDeskName){
        Condition condition = new Condition(CashierDesk.class);
        condition.or().andEqualTo("shopid", shopId)
        .andEqualTo("name", cashierDeskName);
        if(!cashierDeskRepository.findByCondition(condition).isEmpty()) throw new ServiceException(CASHIER_DESK_NAME_EXISTS);
    }



    public InitInfoVO getInitInfo(String deviceId){
        InitInfo initInfo = initInfoRepository.findBy("deviceid", deviceId);
        Boolean isBound = initInfo != null;
        if(isBound) {
            CashierDesk cashierDesk = cashierDeskRepository.findBy("id",initInfo.getCashierdeskid());
            String[] splitDate=cashierDesk.getName().split("\\-");
            if (splitDate.length == 3){
                cashierDesk.setName(splitDate[2]);
            }
            return InitInfoVO.builder()
                    .isBound(true)
                    .shopId(initInfo.getShopid())
                    .cashierDeskId(initInfo.getCashierdeskid())
                    .cashierName(cashierDesk.getName())
                    .build();
        } else {
            return InitInfoVO.builder()
                .isBound(isBound).build();
        }
    }






}
